package me.wangxuan.pat.generator;

import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

public class IdCardGenerator implements IGenerator {

	private static final String[] AREA_CODES = { "110000", "120000", "130000", "140000", "150000", // 北京市, 天津市, 河北省,
																									// 山西省, 内蒙古自治区
			"210000", "220000", "230000", // 辽宁省, 吉林省, 黑龙江省
			"310000", "320000", "330000", "340000", "350000", "360000", "370000", // 上海市, 江苏省, 浙江省, 安徽省, 福建省, 江西省, 山东省
			"410000", "420000", "430000", "440000", "450000", "460000", // 河南省, 湖北省, 湖南省, 广东省, 广西壮族自治区, 海南省
			"500000", "510000", "520000", "530000", "540000", // 重庆市, 四川省, 贵州省, 云南省, 西藏自治区
			"610000", "620000", "630000", "640000", "650000", // 陕西省, 甘肃省, 青海省, 宁夏回族自治区, 新疆维吾尔自治区
			// 可以继续添加更多地区码
	};

	private static final String[] SEX_CODES = { "1", "2" }; // 1代表男性，2代表女性

	@Override
	public GeneratorType getType() {
		return GeneratorType.idCard;
	}

	@Override
	public String generate() {
		Random random = new Random();

		// 生成地区码
		String areaCode = AREA_CODES[random.nextInt(AREA_CODES.length)];
		int thisYear = Calendar.getInstance().get(Calendar.YEAR);
		//log.info("thisYear:{}", thisYear);
		int startYear = thisYear - 65;
		// 生成出生日期码
		int year = startYear + random.nextInt(48); // 65-18
		int month = 1 + random.nextInt(12);
		int day = 0; // 简化处理，假设每个月最多28天
		List<Integer> bigMonths = Arrays.asList(new Integer[]{1,3,5,7,8,10,12});
		List<Integer> smallMonths = Arrays.asList(new Integer[]{4,6,9,11});
		if(bigMonths.contains(month)) {
			day = 1 + random.nextInt(31);
		}else if (smallMonths.contains(month)) {
			day = 1 + random.nextInt(30);
		}else {
			day = 1 + random.nextInt(28);
		}
		String birthDate = String.format("%04d%02d%02d", year, month, day);

		// 生成顺序码
		String sequenceCode = String.format("%03d", random.nextInt(1000));
		sequenceCode = SEX_CODES[random.nextInt(SEX_CODES.length)] + sequenceCode.substring(1);

		// 生成校验码
		String idCardWithoutCheckCode = areaCode + birthDate + sequenceCode;
		char checkCode = calculateCheckCode(idCardWithoutCheckCode);
		String idCard = idCardWithoutCheckCode + checkCode;

		return idCard;
	}

	private static char calculateCheckCode(String idCardWithoutCheckCode) {
		int[] weights = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
		char[] checkCodes = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
		int sum = 0;
		for (int i = 0; i < idCardWithoutCheckCode.length(); i++) {
			sum += (idCardWithoutCheckCode.charAt(i) - '0') * weights[i];
		}
		int remainder = sum % 11;
		return checkCodes[remainder];
	}

}
